
using Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.DomainEntities.Parameters.DomainService;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace SOEI.Solution.DomainEntities.Organization.DomainService
{
    /// <summary>
    /// 领域服务层一个模块的核心业务逻辑
    ///</summary>
    public class OrganiPersonManager : DomainServiceBase, IOrganiPersonManager
    {

        private readonly IRepository<OrganiPerson, long> _organipersonRepository;

        /// <summary>
        /// 【Parameter】参数的领域服务
        /// </summary>
        private readonly IParameterManager _parameterManager;

        /// <summary>
        /// 【OrganiPerson】的构造方法
        /// 通过构造函数注册服务到依赖注入容器中
        ///</summary>
        public OrganiPersonManager(
            IRepository<OrganiPerson, long> organipersonRepository,
            IParameterManager parameterManager


        )
        {
            _organipersonRepository = organipersonRepository;
            _parameterManager = parameterManager;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        /// 返回列表查询用
        /// </summary>
        /// <returns></returns>
        public IQueryable<OrganiPerson> QueryEntityListAsNoTracking()
        {

            var query = _organipersonRepository.GetAll().AsNoTracking()
                        .Select(x => new OrganiPerson
                        {

                            Name = x.Name,
                            Sex = x.Sex,
                            PhoneNumber = x.PhoneNumber,
                            IDNumber = x.IDNumber,
                            CertificateCode = x.CertificateCode,
                            JGBH = x.JGBH,
                            OrganizeID = x.OrganizeID,
                            Remark = x.Remark,
                            ApplyStatus = x.ApplyStatus,
                            DataStatus = x.DataStatus,
                            ApprovalStatus = x.ApprovalStatus,
                            PersonTypeName = "666"

                        });
            return query;
        }

        /// <summary>
        /// 【OrganiPerson】返回表达式数的实体信息即IQueryable类型
        /// </summary>
        /// <returns>IQueryable</returns>
        public IQueryable<OrganiPerson> Query()
        {
            return _organipersonRepository.GetAll();
        }
        /// <summary>
        /// 【OrganiPerson】返回即IQueryable类型的实体，不包含EF Core跟踪标记
        /// </summary>
        /// <returns>IQueryable</returns>
        public IQueryable<OrganiPerson> QueryAsNoTracking()
        {
            return _organipersonRepository.GetAll().AsNoTracking();
        }
        /// <summary>
        /// 【OrganiPerson】根据Id查询实体信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns>实体</returns>
        public async Task<OrganiPerson> FindByIdAsync(long id)
        {
            var entity = await _organipersonRepository.GetAsync(id);
            return entity;
        }
        /// <summary>
        /// 【OrganiPerson】检查实体是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns>bool</returns>
        public async Task<bool> IsExistAsync(long id)
        {
            var result = await _organipersonRepository.GetAll().AnyAsync(a => a.Id == id);
            return result;
        }
        /// <summary>
        /// 【OrganiPerson】创建实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<OrganiPerson> CreateAsync(OrganiPerson entity)
        {
            entity.Id = await _organipersonRepository.InsertAndGetIdAsync(entity);
            return entity;
        }
        /// <summary>
        /// 【OrganiPerson】更新实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task UpdateAsync(OrganiPerson entity)
        {
            await _organipersonRepository.UpdateAsync(entity);
        }
        /// <summary>
        /// 【OrganiPerson】删除实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(long id)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _organipersonRepository.DeleteAsync(id);
        }
        /// <summary>
        /// 【OrganiPerson】批量删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task BatchDelete(List<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _organipersonRepository.DeleteAsync(a => input.Contains(a.Id));
        }
        #endregion


        #region -------------------------------------------------用户自定义------------------------------------------------
        /// <summary>
        /// 通过关联查询获取列表查询结果
        /// </summary>
        /// <returns></returns>
        public IQueryable<OrganiPerson> QueryUnionEntityListAsNoTracking()
        {

            // linqforSql

            // 这里目前必须要把类型查出来然后在联合查询
            var ListEntity = this._parameterManager.QueryPersonType().ToList();
            var query = this.Query().AsNoTracking();

            var result = from x in query
                         join b in ListEntity on x.PersonType equals b.Id into dc
                         from dci in dc.DefaultIfEmpty()

                         select new OrganiPerson
                         {
                             Id = x.Id,
                             Name = x.Name,
                             Sex = x.Sex,
                             PhoneNumber = x.PhoneNumber,
                             IDNumber = x.IDNumber,
                             CertificateCode = x.CertificateCode,
                             JGBH = x.JGBH,
                             OrganizeID = x.OrganizeID,
                             Remark = x.Remark,
                             ApplyStatus = x.ApplyStatus,
                             DataStatus = x.DataStatus,
                             ApprovalStatus = x.ApprovalStatus,
                             PersonType = x.PersonType,

                             /*审计属性*/
                             CreationTime = x.CreationTime,
                             CreatorUserId = x.CreatorUserId,
                             LastModificationTime = x.LastModificationTime,
                             LastModifierUserId = x.LastModifierUserId,

                             PersonTypeName = dci.Value
                         };
            return result;
        }

        /// <summary>
        /// 提交经济机构人员信息（将状态为待提交的数据设置为待审核状态）
        /// </summary>
        /// <param name="OrganizeID">经济机构编号</param>
        /// <returns></returns>
        public async Task SubmitApproval(long OrganizeID)
        {
            // 1. 获取这个机构下的所有状态为1的人员

            var listPersonEntity = await this.Query()
                .Where(x => x.OrganizeID == OrganizeID) // 获取当前机构
                .Where(x => x.ApprovalStatus == Customized.EApprovalStatus.WaitSubmit) // 状态为待提交
                .ToListAsync();

            // 没有提交的人员全部设置为待审核
            foreach (var item in listPersonEntity)
            {
                item.ApprovalStatus = Customized.EApprovalStatus.WaitReview; // 设置为待审核
                await this.UpdateAsync(item);
            }
        }
        #endregion









    }
}
